package com.qf.qfleadnewscommons.mvc;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class UidHeaderInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {

        //获取请求头中的uid
        String uidStr = request.getHeader("uid");

        log.info("当前的uid为：{}",uidStr);

        if (!StringUtils.isEmpty(uidStr)){
            long uid = Long.parseLong(uidStr);

            //存入ThreadLocal
            ThreadLocalUtils.putUid(uid);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //将当前ThreadLocal中的uid删除（防止内存泄露）
        ThreadLocalUtils.removeUid();
    }
}
